//引入侧边栏
import { Layout, Menu } from 'antd';
//引入icon图标
import { SettingFilled, ShoppingFilled, HomeFilled } from '@ant-design/icons';
//引入路由跳转->useNavigate   获取当前页面的url  ->  useLocation
import { useNavigate ,useLocation } from "react-router-dom";
//引入 Hooks 
import { useState } from 'react';
//引入css样式
import "../assets/css/sider.css";

const { Sider } = Layout;



//antd封装好的函数
function getItem(label, key, icon, children, type) {
    return {
        key,
        icon,
        children,
        label,
        type,
    };
}

//封装好的items 侧边栏数据 
const items = [
    getItem('首页', '/home', <HomeFilled />),
    getItem('系统管理', 'sub1', <SettingFilled />, [
        getItem('菜单管理', '/menu'),
        getItem('角色管理', '/role'),
        getItem('管理员管理', '/user'),
    ]),
    getItem('商城管理', 'sub2', <ShoppingFilled />, [
        getItem('商品分类', '/goods'),
    ])

];



export default function Vsider() {
    //设置路由跳转
    const Navigate = useNavigate();
    //获取url  路由名称
    const {pathname} = useLocation();//用useLocation中的pathname获取当前页面的url，得到的是 /xxx
    const newpathname = pathname.replace('/index', '') //去掉 /
    //设置selectedKeys	当前选中的菜单项 key 数组  的初始值
    const [current, setCurrent] = useState(newpathname);

    //设置只能显示一个组件
    const rootSubmenuKeys = ["/home",'sub1', 'sub2'];
    const [openKeys, setOpenKeys] = useState(['/home']);
    const onOpenChange = (keys) => {
        const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
        if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
            setOpenKeys(keys);
        } else {
            setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
        }
    };



    //这是点击每一项 跳转到相应的路由
    const select = (item) => {
        Navigate("/index" + item.key);
        //显示高亮
        setCurrent(item.key);
    };
    return (<div id='sider'>
        <Sider>
            <Menu
                className='menu'
                style={{
                    width: 200,
                }}
                
                selectedKeys={[current]}
                mode="inline"
                items={items}
                //点击跳转相应的路由
                onClick={select}
                //只显示一个父组件
                openKeys={openKeys}
                onOpenChange={onOpenChange}
            />

        </Sider>
    </div>)
}